package com.newhis.common.filter;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.newhis.entity.LoginInfo;
import com.newhis.entity.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Date;

public class AccessRecorderFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(AccessRecorderFilter.class);

    //@Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    //@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;

        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        if(token.equals("token_pass")) {
            setMonitorInfo(httpServletRequest);
            filterChain.doFilter(servletRequest, servletResponse);//到下一个链
        } else {
            // 执行认证
            if (token == null) {
                throw new RuntimeException("无token，请重新登录");
            }
            // 获取 token 中的 user id
            String userId;
            try {
                userId = JWT.decode(token).getAudience().get(0);
            } catch (JWTDecodeException j) {
                throw new RuntimeException("401");
            }
            LoginInfo li = new LoginInfo();  //userService.findUserById(userId);

            if (li == null) {
                throw new RuntimeException("用户不存在，请重新登录");
            }

            // 验证 token
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(li.getAut())).build();
            try {
                jwtVerifier.verify(token);
            } catch (JWTVerificationException e) {
                throw new RuntimeException("401");
            }

            setMonitorInfo(httpServletRequest);
        }



//        String uri = httpServletRequest.getRequestURI();
//        if(uri.endsWith(".css") || uri.endsWith(".js") || uri.endsWith(".woff") || uri.endsWith(".map") || uri.endsWith(".jpg") || uri.endsWith(".png")){
//            filterChain.doFilter(servletRequest , servletResponse);
//            return;
//        }
//
//        String ua = request.getHeader("user-agent");
//        String ip = request.getRemoteAddr();
//
//        Long st = new Date().getTime();
//        //将请求向后送到Controller进行处理
//        filterChain.doFilter(servletRequest , servletResponse);
//        Long et = new Date().getTime();
//        logger.info("uri:{},ip:{},time:{} ms,ua:{}" , uri , ip , (et-st) , ua);
    }

    private void setMonitorInfo(HttpServletRequest hsr) {
        String sqlMonStr = hsr.getHeader("sql_mon");
        SqlMonitorSwitch.setSqlMonStr(sqlMonStr);
        SqlMonitorSwitch.setSqlMonUrl(hsr.getRequestURI());
    }
    //@Override
    public void destroy() {
    }
}